package leetcode.binaryTree;

import utils.printer.BinaryTrees;
import datastructure.tree.BinarySearchTree;
import datastructure.tree.TreeNode;

import java.util.*;

/**
 * @Description: https://leetcode.cn/problems/binary-tree-inorder-traversal/
 * 给定一个二叉树的根节点 root ，返回 它的 中序 遍历 。
 * @Author Ammar
 * @Create 2023/3/29 17:51
 */
public class _94_二叉树的中序遍历 {
    /**
     * 递归
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal1(TreeNode<Integer> root) {
        List<Integer> datas = new ArrayList<>();
        if (root == null) return datas;
        datas.addAll(inorderTraversal(root.left));
        datas.add(root.val);
        datas.addAll(inorderTraversal(root.right));
        return datas;
    }


    /**
     * 迭代
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal2(TreeNode<Integer> root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Deque<TreeNode<Integer>> deque = new ArrayDeque<>();
        while (root != null || !deque.isEmpty()) {
            // 所有左边的节点都入栈
            while (root != null) {
                deque.push(root);
                root = root.left;
            }
            // 出栈的是最左边的节点
            root = deque.pop();
            list.add(root.val);
            root = root.right;
        }
        return list;
    }

    public static List<Integer> inorderTraversal(TreeNode<Integer> root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode<Integer>> stack = new Stack<>();
        while (true) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else if (stack.isEmpty()) {
                return list;
            } else {
                root = stack.pop();
                list.add(root.val);
                // 让右节点进入中序遍历
                root = root.right;
            }
        }
    }

    public static void main(String[] args) {
        Integer[] data = new Integer[]{
                7, 4, 9, 2, 5, 8 ,11, 3, 12, 1
        };
        BinarySearchTree<Integer> binarySearchTree = new BinarySearchTree<>();
        for (int i = 0; i < data.length; i++) {
            binarySearchTree.add(data[i]);
        }
        BinaryTrees.print(binarySearchTree);
        List<Integer> integers = inorderTraversal(binarySearchTree.getRoot());
        integers.forEach(System.out::println);
    }
}
